package cn.globalph.housekeeper.ui.task

import android.graphics.Bitmap
import cn.globalph.housekeeper.data.model.*
import cn.globalph.housekeeper.data.params.SignDataParam
import cn.globalph.housekeeper.data.params.SignParam
import cn.globalph.housekeeper.data.params.StartTaskParam
import cn.globalph.housekeeper.data.retrofit.HttpConstant
import cn.globalph.housekeeper.data.retrofit.HttpManager
import cn.globalph.housekeeper.utils.BitmapUtil
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import okhttp3.MultipartBody

class TaskRepository(
    private val httpManager: HttpManager
) {
    suspend fun getDailyTasks(date: String): BaseModel<List<Task>> {
        return httpManager.api.getDailyTasks(date)
    }

    suspend fun getProfiles(): BaseModel<ProfilesModel> {
        return httpManager.api.getCompleteProfile()
    }

    suspend fun switchRole(providerid: String, roleid: String): BaseModel<LoginModel> {
        return httpManager.api.switchRole(providerid, roleid)
    }

    suspend fun startService(param: StartTaskParam): BaseModel<StartServerModel> {
        return httpManager.api.startService(param)
    }

    suspend fun getCustomSignToken(
        id: String,
        fileName: String,
        bitmap: Bitmap
    ): BaseModel<out StartServerModel> {
        return withContext(Dispatchers.IO) {
            val file =
                BitmapUtil.bitmapToBase64(bitmap) ?: return@withContext BaseModel(
                    -1,
                    "未获取到用户签名",
                    null
                )
            val tokenModel = httpManager.api.getCustomSignToken(fileName)
            if (tokenModel.isSuccessful()) {
                val data = tokenModel.data
                data?.let {
                    val requestBody = MultipartBody.Builder().setType(MultipartBody.FORM)
                        .addFormDataPart("key", it.key)
                        .addFormDataPart("token", it.token)
                        .addFormDataPart("file", file)
                        .build()

                    httpManager.api.uploadCustomSign(HttpConstant.FILE_URL, requestBody)
                    return@withContext httpManager.api.uploadCustomSignData(
                        SignDataParam(
                            id,
                            it.downloadFilePath
                        )
                    )
                }
            }
            return@withContext BaseModel(-1, tokenModel.message, null)
        }
    }

    suspend fun getCheckInfo(id:String):BaseModel<String>{
        return httpManager.api.getCheckInfo(id)
    }
}